﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace com.sharepointutils.application
{
    public class SharePointSOAPRequest
    {
        public static String Run(String siteURL, String soapAction, NetworkCredential credentials, String message)
        {
            String result = String.Empty;
            try
            {
                Uri requestURI = new Uri(siteURL + "/_vti_bin/lists.asmx");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestURI);
                request.Accept = "text/xml; charset=utf-8";
                request.ContentType = "text/xml; charset=utf-8";
                request.Headers.Add("SOAPAction", "\"" + soapAction + "\"");
                request.Credentials = credentials;
                request.Method = "POST";
                request.ContentLength = Encoding.UTF8.GetByteCount(message);

                using (Stream writer = request.GetRequestStream())
                {
                    writer.Write(Encoding.UTF8.GetBytes(message), 0, Encoding.UTF8.GetByteCount(message));
                }

                using (WebResponse response = request.GetResponse())
                {
                    StreamReader sr = new StreamReader(response.GetResponseStream());
                    result = sr.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                StreamReader sr = new StreamReader(ex.Response.GetResponseStream());
                result = sr.ReadToEnd();
            }
            return result;
        }
    }
}
